import { LitElement, html, css } from 'lit';
import { customElement, property } from 'lit/decorators.js';

interface TableColumn {
  prop: string;
  label: string;
  width?: string;
  align?: 'left' | 'center' | 'right';
}

interface TableData {
  [key: string]: any;
}

/**
 * Table表格组件
 * @element zss-table
 * @slot - 表格内容插槽
 */
@customElement('zss-table')
export class ZssTable extends LitElement {
  static styles = css`
    :host {
      display: block;
      width: 100%;
    }
    
    .table-container {
      width: 100%;
      overflow: auto;
      border: 1px solid var(--zss-border-color);
      border-radius: var(--zss-border-radius-base);
    }
    
    .table {
      width: 100%;
      border-collapse: collapse;
      border-spacing: 0;
      font-size: var(--zss-font-size-base);
      color: var(--zss-text-color-regular);
    }
    
    .table th,
    .table td {
      padding: 12px 8px;
      border-bottom: 1px solid var(--zss-border-color);
      text-align: left;
    }
    
    .table th {
      background-color: var(--zss-fill-color-light);
      color: var(--zss-text-color-primary);
      font-weight: 600;
    }
    
    .table th.center,
    .table td.center {
      text-align: center;
    }
    
    .table th.right,
    .table td.right {
      text-align: right;
    }
    
    .table tbody tr:hover {
      background-color: var(--zss-fill-color-light);
    }
    
    .table tbody tr.selected {
      background-color: var(--zss-color-primary-light-9);
    }
    
    .empty-text {
      text-align: center;
      padding: 40px 0;
      color: var(--zss-text-color-placeholder);
    }
    
    .pagination {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      margin-top: 16px;
      padding: 0 16px;
    }
    
    .pagination-info {
      margin-right: 16px;
      color: var(--zss-text-color-regular);
    }

    /* 斑马纹 */
    :host([stripe]) .table tbody tr:nth-child(even) {
      background-color: var(--zss-fill-color-light);
    }

    :host([stripe]) .table tbody tr:nth-child(even):hover {
      background-color: var(--zss-fill-color);
    }

    /* 边框 */
    :host([border]) .table th,
    :host([border]) .table td {
      border-right: 1px solid var(--zss-border-color);
    }

    :host([border]) .table th:last-child,
    :host([border]) .table td:last-child {
      border-right: none;
    }

    /* 尺寸 */
    :host([size="small"]) .table th,
    :host([size="small"]) .table td {
      padding: 8px;
    }

    :host([size="large"]) .table th,
    :host([size="large"]) .table td {
      padding: 16px 12px;
    }
  `;

  /**
   * 表格列配置
   */
  @property({ type: Array })
  columns: TableColumn[] = [];

  /**
   * 表格数据
   */
  @property({ type: Array })
  data: TableData[] = [];

  /**
   * 是否显示边框
   * @attr border
   */
  @property({ type: Boolean })
  border = false;

  /**
   * 是否显示斑马纹
   * @attr stripe
   */
  @property({ type: Boolean })
  stripe = false;

  /**
   * 是否支持多选
   * @attr selection
   */
  @property({ type: Boolean })
  selection = false;

  /**
   * 是否显示加载状态
   * @attr loading
   */
  @property({ type: Boolean })
  loading = false;

  /**
   * 尺寸
   * @attr size
   */
  @property({ type: String })
  size: 'small' | 'default' | 'large' = 'default';

  /**
   * 空数据时显示的文本
   * @attr empty-text
   */
  @property({ type: String })
  emptyText = '暂无数据';

  /**
   * 当前选中行
   */
  @property({ type: Array })
  selectedRows: TableData[] = [];

  /**
   * 是否显示分页
   * @attr pagination
   */
  @property({ type: Boolean })
  pagination = false;

  /**
   * 当前页码
   * @attr current-page
   */
  @property({ type: Number })
  currentPage = 1;

  /**
   * 每页显示数量
   * @attr page-size
   */
  @property({ type: Number })
  pageSize = 10;

  /**
   * 总数据量
   * @attr total
   */
  @property({ type: Number })
  total = 0;

  private handleRowClick(row: TableData, _index?: number): void {
    if (this.selection) {
      const selectedIndex = this.selectedRows.findIndex(selectedRow => 
        selectedRow === row
      );
      
      if (selectedIndex > -1) {
        this.selectedRows.splice(selectedIndex, 1);
      } else {
        this.selectedRows.push(row);
      }
      
      this.requestUpdate();
      this.dispatchEvent(new CustomEvent('select', { 
        detail: { selectedRows: this.selectedRows } 
      }));
    }
  }

  private getPagedData(): TableData[] {
    if (!this.pagination) {
      return this.data;
    }
    
    const start = (this.currentPage - 1) * this.pageSize;
    const end = start + this.pageSize;
    return this.data.slice(start, end);
  }

  render() {
    const pagedData = this.getPagedData();
    const totalPages = Math.ceil(this.total / this.pageSize);

    return html`
      <table class="table ${this.border ? 'border' : ''} ${this.stripe ? 'stripe' : ''}">
        <thead>
          <tr>
            ${this.columns.map(column => html`
              <th 
                class=${column.align || 'left'}
                style=${column.width ? `width: ${column.width}` : ''}
              >
                ${column.label}
              </th>
            `)}
          </tr>
        </thead>
        <tbody>
          ${pagedData.length === 0 ? html`
            <tr>
              <td colspan=${this.columns.length} class="empty-text">
                暂无数据
              </td>
            </tr>
          ` : pagedData.map((row, index) => html`
            <tr 
              class=${this.selectedRows.includes(row) ? 'selected' : ''}
              @click=${() => this.handleRowClick(row, index)}
              style="cursor: ${this.selection ? 'pointer' : 'default'}"
            >
              ${this.columns.map(column => html`
                <td class=${column.align || 'left'}>
                  ${row[column.prop] || ''}
                </td>
              `)}
            </tr>
          `)}
        </tbody>
      </table>
      
      ${this.pagination ? html`
        <div class="pagination">
          <span class="pagination-info">
            第 ${this.currentPage} 页，共 ${totalPages} 页
          </span>
          <!-- 分页器组件可以在这里实现 -->
        </div>
      ` : ''}
    `;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'zss-table': ZssTable;
  }
}